package com.scud.common.filter;

import com.alibaba.fastjson.JSON;
import com.scud.common.utils.JwtUtil;
import com.scud.model.system.pojo.User;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.DispatcherServlet;

import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author vermouth
 */
@Component
@ConditionalOnClass(DispatcherServlet.class)
@Slf4j
public class JwtFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //获取token
        String token = request.getHeader("token");
        if (token == null) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        System.out.println(token);
        //解析token,放入springSecurity的上下文当中
        Map<String, Object> claims = null;
        try {
            claims = JwtUtil.parseJWT("scud", token);
        } catch (Exception e) {
            e.printStackTrace();
            filterChain.doFilter(request, response);
            return;
        }

        //获取用户id
        Long userId = Long.valueOf(claims.get("user_id").toString());
        User user = User.builder()
                .id(userId)
                .build();
        String json = JSON.toJSONString(user);
        //获取权限信息
//        List<?> permissionsList = (List<?>) claims.get("permissions");
        List<?> permissionsList = claims.get("permissions") instanceof List ? (List<?>) claims.get("permissions") : new ArrayList<>();
        log.info("permissionList is {}",permissionsList);
        Collection<? extends GrantedAuthority> permissions = permissionsList.stream()
                .map(permission -> new SimpleGrantedAuthority(permission.toString().substring(11,permission.toString().length()-1)))
                .collect(Collectors.toList());
//        List<SimpleGrantedAuthority> permissions = (List<SimpleGrantedAuthority>) claims.get("permissions");
        log.info("过滤器，当前的用户权限为：{}",permissions);
        Authentication authentication = new UsernamePasswordAuthenticationToken(json, token, permissions);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }
}
